<template>
  <div class="statistics-dashboard">
    <!-- 顶部关键指标 -->
    <el-row :gutter="20" class="metrics-row">
      <el-col :xs="12" :sm="6" :lg="6">
        <div class="metric-card completed">
          <div class="metric-icon">
            <i class="el-icon-check"></i>
          </div>
          <div class="metric-content">
            <div class="metric-title">累计完成维修</div>
            <div class="metric-value">{{ metrics.completedRepairs }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="6">
        <div class="metric-card repairing">
          <div class="metric-icon">
            <i class="el-icon-loading"></i>
          </div>
          <div class="metric-content">
            <div class="metric-title">维修中</div>
            <div class="metric-value">{{ metrics.repairing }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="6">
        <div class="metric-card reworking">
          <div class="metric-icon">
            <i class="el-icon-refresh"></i>
          </div>
          <div class="metric-content">
            <div class="metric-title">追加工中</div>
            <div class="metric-value">{{ metrics.reworking }}</div>
          </div>
        </div>
      </el-col>
      <el-col :xs="12" :sm="6" :lg="6">
        <div class="metric-card waiting">
          <div class="metric-icon">
            <i class="el-icon-time"></i>
          </div>
          <div class="metric-content">
            <div class="metric-title">待料中</div>
            <div class="metric-value">{{ metrics.waitingForMaterial }}</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 中间图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :sm="12" :lg="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>故障类型饼状图</span>
          </div>
          <div ref="faultTypePieChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>近30天报修次数折线图</span>
          </div>
          <div ref="repairCountLineChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <el-col :xs="24" :sm="12" :lg="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>维修工修理花费平均时长柱状图</span>
            <div class="chart-filters">
              <el-select v-model="filters.faultType" placeholder="故障类型" size="small" style="width: 120px; margin-right: 10px;">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="type in faultTypes" :key="type.value" :label="type.label" :value="type.value"></el-option>
              </el-select>
              <el-select v-model="filters.timeRange" placeholder="时间范围" size="small" style="width: 120px;">
                <el-option label="当前周" value="week"></el-option>
                <el-option label="当前月" value="month"></el-option>
                <el-option label="当前年" value="year"></el-option>
              </el-select>
            </div>
          </div>
          <div ref="repairDurationChart" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :lg="12">
        <el-card class="chart-card">
          <div slot="header" class="chart-header">
            <span>维修工维修次数柱状图</span>
            <div class="chart-filters">
              <el-select v-model="filters.faultType2" placeholder="故障类型" size="small" style="width: 120px; margin-right: 10px;">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="type in faultTypes" :key="type.value" :label="type.label" :value="type.value"></el-option>
              </el-select>
              <el-select v-model="filters.timeRange2" placeholder="时间范围" size="small" style="width: 120px;">
                <el-option label="当前周" value="week"></el-option>
                <el-option label="当前月" value="month"></el-option>
                <el-option label="当前年" value="year"></el-option>
              </el-select>
            </div>
          </div>
          <div ref="repairCountChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getMetrics, getFaultTypeDistribution, getRepairCountTrend, getRepairDurationStats, getRepairCountStats, getFaultTypes } from '@/api/dashboard/statistics'

export default {
  name: 'StatisticsDashboard',
  data() {
    return {
      // 关键指标数据
      metrics: {
        completedRepairs: 0,
        repairing: 0,
        reworking: 0,
        waitingForMaterial: 0
      },
      // 筛选条件
      filters: {
        faultType: '',
        timeRange: 'week',
        faultType2: '',
        timeRange2: 'week'
      },
      // 故障类型选项
      faultTypes: [],
      // 图表实例
      charts: {
        faultTypePie: null,
        repairCountLine: null,
        repairDuration: null,
        repairCount: null
      }
    }
  },
  mounted() {
    this.initCharts()
    this.loadData()
    this.loadFaultTypes()
  },
  beforeDestroy() {
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
  },
  watch: {
    // 监听筛选条件变化
    'filters.faultType'() {
      this.refreshDurationChart()
    },
    'filters.timeRange'() {
      this.refreshDurationChart()
    },
    'filters.faultType2'() {
      this.refreshCountChart()
    },
    'filters.timeRange2'() {
      this.refreshCountChart()
    }
  },
  methods: {
    // 初始化图表
    initCharts() {
      this.$nextTick(() => {
        this.initFaultTypePieChart()
        this.initRepairCountLineChart()
        this.initRepairDurationChart()
        this.initRepairCountChart()
      })
    },

    // 故障类型饼状图
    initFaultTypePieChart() {
      this.charts.faultTypePie = echarts.init(this.$refs.faultTypePieChart)
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '故障类型',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      this.charts.faultTypePie.setOption(option)
    },

    // 近30天报修次数折线图
    initRepairCountLineChart() {
      this.charts.repairCountLine = echarts.init(this.$refs.repairCountLineChart)
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '报修次数',
            type: 'line',
            data: [],
            smooth: true,
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      }
      this.charts.repairCountLine.setOption(option)
    },

    // 维修工修理花费平均时长柱状图
    initRepairDurationChart() {
      this.charts.repairDuration = echarts.init(this.$refs.repairDurationChart)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          name: '平均时长(小时)'
        },
        series: [
          {
            name: '平均时长',
            type: 'bar',
            data: [],
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      }
      this.charts.repairDuration.setOption(option)
    },

    // 维修工维修次数柱状图
    initRepairCountChart() {
      this.charts.repairCount = echarts.init(this.$refs.repairCountChart)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          name: '维修次数'
        },
        series: [
          {
            name: '维修次数',
            type: 'bar',
            data: [],
            itemStyle: {
              color: '#E6A23C'
            }
          }
        ]
      }
      this.charts.repairCount.setOption(option)
    },

    // 生成最近30天的日期
    generateLast30Days() {
      const days = []
      for (let i = 29; i >= 0; i--) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        days.push(date.getMonth() + 1 + '/' + date.getDate())
      }
      return days
    },



    // 加载数据
    loadData() {
      this.fetchMetrics()
      this.fetchChartData()
    },

    // 加载故障类型列表
    async loadFaultTypes() {
      try {
        const response = await getFaultTypes()
        if (response.code === 200) {
          this.faultTypes = response.data
        }
      } catch (error) {
        console.error('获取故障类型列表失败:', error)
        // 设置默认值
        this.faultTypes = [
          { label: '机械故障', value: '机械故障' },
          { label: '电气故障', value: '电气故障' },
          { label: '液压故障', value: '液压故障' },
          { label: '软件故障', value: '软件故障' }
        ]
      }
    },

    // 获取关键指标数据
    async fetchMetrics() {
      try {
        const response = await getMetrics()
        if (response.code === 200) {
          this.metrics = response.data
        }
      } catch (error) {
        console.error('获取关键指标数据失败:', error)
        // 设置默认值
        this.metrics = {
          completedRepairs: 0,
          repairing: 0,
          reworking: 0,
          waitingForMaterial: 0
        }
      }
    },

    // 获取图表数据
    async fetchChartData() {
      try {
        // 获取故障类型分布数据
        const faultTypeResponse = await getFaultTypeDistribution()
        if (faultTypeResponse.code === 200) {
          this.updateFaultTypePieChart(faultTypeResponse.data)
        }

        // 获取报修趋势数据
        const trendResponse = await getRepairCountTrend()
        if (trendResponse.code === 200) {
          this.updateRepairCountLineChart(trendResponse.data)
        }

        // 获取维修时长数据
        const durationResponse = await getRepairDurationStats({
          faultType: this.filters.faultType,
          timeRange: this.filters.timeRange
        })
        if (durationResponse.code === 200) {
          this.updateRepairDurationChart(durationResponse.data)
        }

        // 获取维修次数数据
        const countResponse = await getRepairCountStats({
          faultType: this.filters.faultType2,
          timeRange: this.filters.timeRange2
        })
        if (countResponse.code === 200) {
          this.updateRepairCountChart(countResponse.data)
        }
      } catch (error) {
        console.error('获取图表数据失败:', error)
      }
    },

    // 更新故障类型饼状图
    updateFaultTypePieChart(data) {
      if (this.charts.faultTypePie) {
        this.charts.faultTypePie.setOption({
          series: [{
            data: data
          }]
        })
      }
    },

    // 更新报修次数折线图
    updateRepairCountLineChart(data) {
      if (this.charts.repairCountLine) {
        this.charts.repairCountLine.setOption({
          xAxis: {
            data: data.dates
          },
          series: [{
            data: data.counts
          }]
        })
      }
    },

    // 更新维修时长柱状图
    updateRepairDurationChart(data) {
      if (this.charts.repairDuration) {
        const names = data.map(item => item.name)
        const durations = data.map(item => item.duration)

        this.charts.repairDuration.setOption({
          xAxis: {
            data: names
          },
          series: [{
            data: durations
          }]
        })
      }
    },

    // 更新维修次数柱状图
    updateRepairCountChart(data) {
      if (this.charts.repairCount) {
        const names = data.map(item => item.name)
        const counts = data.map(item => item.count)

        this.charts.repairCount.setOption({
          xAxis: {
            data: names
          },
          series: [{
            data: counts
          }]
        })
      }
    },

    // 刷新维修时长图表
    async refreshDurationChart() {
      try {
        const response = await getRepairDurationStats({
          faultType: this.filters.faultType,
          timeRange: this.filters.timeRange
        })
        if (response.code === 200) {
          this.updateRepairDurationChart(response.data)
        }
      } catch (error) {
        console.error('刷新维修时长图表失败:', error)
      }
    },

    // 刷新维修次数图表
    async refreshCountChart() {
      try {
        const response = await getRepairCountStats({
          faultType: this.filters.faultType2,
          timeRange: this.filters.timeRange2
        })
        if (response.code === 200) {
          this.updateRepairCountChart(response.data)
        }
      } catch (error) {
        console.error('刷新维修次数图表失败:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.metrics-row {
  margin-bottom: 20px;
}

.metric-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  }

  .metric-icon {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 15px;
    font-size: 24px;
    color: white;
  }

  .metric-content {
    flex: 1;

    .metric-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
    }

    .metric-value {
      font-size: 28px;
      font-weight: bold;
      color: #333;
    }
  }

  &.completed .metric-icon {
    background: linear-gradient(135deg, #67C23A, #85CE61);
  }

  &.repairing .metric-icon {
    background: linear-gradient(135deg, #409EFF, #66B1FF);
  }

  &.reworking .metric-icon {
    background: linear-gradient(135deg, #E6A23C, #EEBE77);
  }

  &.waiting .metric-icon {
    background: linear-gradient(135deg, #F56C6C, #F78989);
  }
}

.charts-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    color: #333;

    .chart-filters {
      display: flex;
      align-items: center;
    }
  }

  .chart-container {
    height: 320px;
    width: 100%;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .statistics-dashboard {
    padding: 10px;
  }

  .metric-card {
    padding: 15px;

    .metric-icon {
      width: 50px;
      height: 50px;
      font-size: 20px;
    }

    .metric-content {
      .metric-title {
        font-size: 12px;
      }

      .metric-value {
        font-size: 24px;
      }
    }
  }

  .chart-card {
    height: 350px;

    .chart-container {
      height: 270px;
    }
  }
}
</style>
